//
//  ViewController.m
//  AutolayoutCell
//
//  Created by aron on 2017/5/22.
//  Copyright © 2017年 aron. All rights reserved.
//

#import "ViewController.h"
#import "AutolayoutCell.h"
#import "GameModel.h"
#import <YYModel/YYModel.h>
#import "TagViewUtils.h"

@interface ViewController ()
@property (nonatomic, strong) NSMutableArray* datas;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"ShowBorder" style:UIBarButtonItemStylePlain target:self action:@selector(onShowBorder)];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"ShowTagView" style:UIBarButtonItemStylePlain target:self action:@selector(onShowTag)];

    self.view.backgroundColor = [UIColor whiteColor];
    self.tableView.estimatedRowHeight = 200;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

    // datas
    _datas = [NSMutableArray array];

    NSString* path = [[NSBundle mainBundle] pathForResource:@"gamelist.json" ofType:nil];
    NSData* data = [NSData dataWithContentsOfFile:path];
    NSArray* jsonObj = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
    if ([jsonObj isKindOfClass:[NSArray class]]) {
        for (NSDictionary* jsonItem in jsonObj) {
            if ([jsonItem isKindOfClass:[NSDictionary class]]) {
                GameModel* gameModel = [GameModel yy_modelWithDictionary:jsonItem];
                [_datas addObject:gameModel];
            }
        }
    }
     
    // retister cell
    [self.tableView registerClass:[AutolayoutCell class] forCellReuseIdentifier:NSStringFromClass([AutolayoutCell class])];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - ......::::::: action :::::::......

- (void)onShowBorder {
    [TagViewUtils recursiveSetBorderWithView:self.view];
}

- (void)onShowTag {
    [TagViewUtils recursiveShowTagWithView:self.view];
}

#pragma mark - ......::::::: UITableViewDelegate :::::::......

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _datas.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    AutolayoutCell* cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([AutolayoutCell class])];
    GameModel* gameModel = _datas[indexPath.row];
    [cell loadData:gameModel indexPath:indexPath];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath];
    [TagViewUtils showTaggingViewWithView:cell.contentView];
}

@end
